package com.eric.demo.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ZhangGuangyin on 2018/6/30
 * 循环打印，m个线程打印n个数
 */
public class LoopPrint {

    public static void main(String[] argvs){
        int maxNum = 100;
        int threadNum = 12;
        AtomicInteger currentNum = new AtomicInteger(0);
        for(int i=0;i<threadNum;i++){
            Thread thread = new Thread(new PrintThread(maxNum, currentNum, i, threadNum));
            thread.setName("打印线程" + i);
            thread.start();
        }

    }

    static class PrintThread implements Runnable{

        private int maxNum;

        private AtomicInteger currentNum;

        private int threadId;

        private int threadNum;

        public PrintThread(int maxNum, AtomicInteger currentNum, int threadId, int threadNum) {
            this.maxNum = maxNum;
            this.currentNum = currentNum;
            this.threadId = threadId;
            this.threadNum = threadNum;
        }

        @Override
        public void run() {
            try {
                synchronized (currentNum) {
                    while (this.currentNum.get() <= this.maxNum){
                        currentNum.notifyAll();
                        if(this.currentNum.get() % threadNum == threadId){
                            System.out.println(Thread.currentThread().getName() + " 打印 " + currentNum.get());
                            currentNum.getAndAdd(1);
                        }
                        currentNum.wait();
                    }
                    currentNum.notifyAll();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
